package com.jizi.machine.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author song1
 * @version 1.0.0
 * @since 2025/4/8
 */
@Slf4j
public class XianyuSearchUtils {

    public static void extracted(String apiString, String email, Set<String> idSet) throws UnsupportedEncodingException {

        // 解析URL
        String url = apiString.split(" ")[1].replace("'", "");

        // 解析Headers
        Map<String, String> headers = new HashMap<>();
        String[] headerParts = apiString.split(" -H '");
        for (int i = 1; i < headerParts.length; i++) {
            String header = headerParts[i].split("'")[0];
            String[] headerKeyValue = header.split(": ");
            headers.put(headerKeyValue[0], headerKeyValue[1]);
        }

        // 解析Cookies
        String cookies = "";
        if (apiString.contains(" -b '")) {
            cookies = apiString.split(" -b '")[1].split("'")[0];
        }

        // 解析请求体
        String requestBody = apiString.split("--data-raw '")[1].split("'")[0].split("=")[1];
        requestBody = URLDecoder.decode(requestBody, StandardCharsets.UTF_8.toString());

        // 发送POST请求
        HttpRequest request = HttpRequest.post(url)
                .timeout(20000); // 设置超时时间（毫秒）

        // 设置Headers
        headers.forEach(request::header);

        // 设置Cookies
        request.cookie(cookies);

        // 设置请求体
        request.body("data=" + URLEncoder.encode(requestBody, StandardCharsets.UTF_8.toString()));

        // 执行请求并获取响应
        HttpResponse response = request.execute();

        // 解析响应
        JSONObject jsonResponse = new JSONObject(response.body());

        // 解析响应的信息，获取商品列表，前五的商品信息
        JSONArray itemsArray = jsonResponse.getJSONObject("data").getJSONArray("resultList");

        String html = "<!DOCTYPE html>\n" +
                "<html lang=\"zh-CN\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "    <title>商品信息</title>\n" +
                "    <style>\n" +
                "        body {\n" +
                "            font-family: Arial, sans-serif;\n" +
                "            line-height: 1.6;\n" +
                "            background-color: #f9f9f9;\n" +
                "            margin: 0;\n" +
                "            padding: 0;\n" +
                "        }\n" +
                "        .container {\n" +
                "            max-width: 600px;\n" +
                "            margin: 20px auto;\n" +
                "            background: #ffffff;\n" +
                "            border-radius: 8px;\n" +
                "            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\n" +
                "            padding: 20px;\n" +
                "        }\n" +
                "        .header {\n" +
                "            text-align: center;\n" +
                "            padding: 10px 0;\n" +
                "            border-bottom: 1px solid #ddd;\n" +
                "        }\n" +
                "        .header h1 {\n" +
                "            margin: 0;\n" +
                "            font-size: 24px;\n" +
                "            color: #333;\n" +
                "        }\n" +
                "        .content {\n" +
                "            padding: 20px 0;\n" +
                "        }\n" +
                "        .content p {\n" +
                "            margin: 10px 0;\n" +
                "            font-size: 16px;\n" +
                "            color: #555;\n" +
                "        }\n" +
                "        .content a {\n" +
                "            color: #1a73e8;\n" +
                "            text-decoration: none;\n" +
                "        }\n" +
                "        .footer {\n" +
                "            text-align: center;\n" +
                "            padding: 10px 0;\n" +
                "            border-top: 1px solid #ddd;\n" +
                "            font-size: 14px;\n" +
                "            color: #999;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <div class=\"container\">\n" +
                "        <div class=\"header\">\n" +
                "            <h1>商品信息</h1>\n" +
                "        </div>\n" +
                "        <div class=\"content\">\n" +
                "            <p><strong>商品价格：</strong>{}</p>\n" +
                "            <p><strong>发布时间：</strong>{}</p>\n" +
                "            <p><strong>商品名称：</strong>{}</p>\n" +
                "            <p><strong>商品链接：</strong><a href=\"{}\" target=\"_blank\">链接</a></p>\n" +
                "        </div>\n" +
                "        <div class=\"footer\">\n" +
                "            <p>此邮件为系统自动发送，请勿回复。</p>\n" +
                "        </div>\n" +
                "    </div>\n" +
                "</body>\n" +
                "</html>";

        // 打印商品信息
        for (int i = 0; i < 5; i++) {
            JSONObject item = itemsArray.getJSONObject(i);
            JSONObject jsonObject = item.getJSONObject("data").getJSONObject("item").getJSONObject("main").getJSONObject("exContent").getJSONObject("detailParams");
            JSONObject tagListJson = item.getJSONObject("data").getJSONObject("item").getJSONObject("main").getJSONObject("exContent").getJSONObject("fishTags").getJSONObject("r2").getJSONArray("tagList").getJSONObject(0);
            String content = tagListJson.getJSONObject("data").getStr("content");
            if (ObjectUtil.isEmpty(jsonObject)) {
                continue;
            }

            JSONObject arg = item.getJSONObject("data").getJSONObject("item").getJSONObject("main").getJSONObject("clickParam").getJSONObject("args");
            String urlTwo = "https://www.goofish.com/item?spm=a21ybx.search.searchFeedList.1.3f356170yBnMij&id={}&categoryId={}";
            if (idSet.contains(arg.getStr("id"))) {
                continue;
            }
            idSet.add(arg.getStr("id"));
            urlTwo = StrUtil.format(urlTwo, arg.getStr("id"), arg.getStr("cCatId"));

            log.info("发布时间：{}", content);
            log.info("商品名称：{}", jsonObject.getStr("title"));
            log.info("商品价格: {}", jsonObject.get("soldPrice"));
            log.info("商品链接: {}", urlTwo);
            log.info("-------------------------------------------------------------------");
            String htmlTwo = StrUtil.format(html, jsonObject.get("soldPrice"), content, jsonObject.getStr("title") , urlTwo);

            MailUtil.send(email, "新上架商品", htmlTwo, true);
        }
    }
}
